package com.spider.silence.downloader;

import com.alibaba.fastjson.JSONObject;
import com.spider.silence.abstarct.downloader.AbstractCommonDownLoader;
import com.spider.silence.task.ChengDuWanBaoTask;
import com.spider.silence.task.InformantCenterForSiChuanTask;
import com.spider.silence.task.manager.CommonTaskManager;
import com.spider.silence.utils.DateUtils;
import com.spider.silence.utils.FileUtils;
import com.spider.silence.utils.MD5Utils;
import com.spider.silence.utils.PropertiesUtil;
import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import us.codecraft.webmagic.Page;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by admin on 2017/7/4.
 * 成都晚报的下载器
 */
public class ChengDuWanBaoDownloader extends AbstractCommonDownLoader {

    private Logger logger =Logger.getLogger(ChengDuWanBaoDownloader.class);

    private Map<String,File> files = null;

    public Map<String, File> getFiles() {
        return files;
    }

    private final String index_site = "http://www.cdwb.com.cn/html/"
            + Calendar.getInstance().get(Calendar.YEAR) + "-"
            + String.format("%02d", (Calendar.getInstance().get(Calendar.MONTH)+1)) + "/"
            + String.format("%02d", Calendar.getInstance().get(Calendar.DAY_OF_MONTH));

    //版块
    private final String[] section = {
            index_site + "/node_282.htm",
            index_site + "/node_283.htm",
            index_site + "/node_284.htm",
            index_site + "/node_285.htm",
            index_site + "/node_286.htm",
            index_site + "/node_287.htm",
            index_site + "/node_288.htm",
            index_site + "/node_289.htm",
            index_site + "/node_301.htm",
            index_site + "/node_302.htm",
            index_site + "/node_303.htm",
            index_site + "/node_304.htm",
            index_site + "/node_305.htm"
    };



    //生成爬虫任务
    public void generateTask(){
        for(int i = 0; i < section.length; i++) {
            try {
                Page page = getHtml(section[i]);
                if(page != null && page.getHtml() != null && page.getStatusCode() == 200) {
                    Document document = page.getHtml().getDocument();
                    Elements elements = document.select("ul[id=\"o_news\"] > ul > li");
                    if(elements.size() > 0) {
                        for(int j = 0; j < elements.size(); j++) {
                            String url = index_site + "/" + elements.get(j).select("a").attr("href");
                            ChengDuWanBaoTask task = new ChengDuWanBaoTask(url);
                            CommonTaskManager.add("ChengDuWanBao", task);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage(),e);
                continue;
            }
        }
    }

    public JSONObject crawlItem(String url) throws Exception {
        JSONObject item = new JSONObject();
        JSONObject data;
        boolean success = false;
        long startTime = System.currentTimeMillis();
        long nowTime = startTime;
        while (nowTime - startTime < Long.valueOf(PropertiesUtil.getVal("ChengDuWanBao.timeOut"))) {
            data = new JSONObject();
            data.put("url", url);
            nowTime = System.currentTimeMillis();
            try {
                Page page = this.getHtml(url,true);
                if(page != null && page.getStatusCode() == 200) {
                    Document document = page.getHtml().getDocument();
                    String title = document.title();
                    data.put("title", title);
                    String publish_time = document.select("div[class=\"M_mode\"] div[class=\"M_cont\"] > p[class=\"info\"] > font").get(0).text().substring(0, 9);
                    publish_time = (publish_time.replace(" ", " ")).replace("年", "-").replace("月", "-").replace("日", "");
                    String[] publish_time_array = publish_time.split("-");
                    publish_time = publish_time_array[0] + "-" + String.format("%02d", Integer.parseInt(publish_time_array[1])) + "-" + String.format("%02d", Integer.parseInt(publish_time_array[2])) + " 00:00:00";
                    publish_time = DateUtils.strToFormatStr(publish_time);
                    data.put("publish_time", publish_time); //新闻发布时间
                    data.put("spider_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));//爬取时间
                    Elements main_elements = document.select("div[class =\"M_m_cont\"]");
                    Elements imgElements = main_elements.select("table[bgcolor=\"#efefef\"] > tbody > tr > td > TABLE > TBODY > TR > TD > IMG");
                    if(imgElements.size() > 0) {
                        List<String> img_urls = new ArrayList<>();
                        for(int i = 0; i < imgElements.size(); i++) {
                            String img = imgElements.get(i).attr("src");
                            img = "http://www.cdwb.com.cn/" + img.substring(img.indexOf("res"));
                            img_urls.add(img);
                        }
                        data.put("img_urls", img_urls.toArray());
                    }

                    Elements content_elements = main_elements.select("table > tbody > tr > td > founder-content > p");
                    if(content_elements.size() > 0) {
                        StringBuilder content = new StringBuilder();
                        for(int i = 0; i < content_elements.size(); i++) {
                            content.append(content_elements.get(i).text().trim());
                        }
                        data.put("content", content);
                    }

                    String newid = url.substring(url.indexOf("content_")+8, url.length()-4);
                    data.put("id", newid);
                    //设置html文件的命名格式
                    String fileName = "ChengDuWanBao" + "_" + DateUtils.dateToTimestamp( DateUtils.parseDate(publish_time)).getTime() + "_" + MD5Utils.getHash3(url.replaceAll("#.*", ""), "MD5");
                    String publishDate = DateUtils.formatDate(DateUtils.parseDate(publish_time)).replace("-","-");
                    String all_fileName = "成都晚报_speeches_" + publishDate + "_" + fileName;
                    //抓取第一页的网页源码
                    File file = FileUtils.createTempFile(all_fileName + "_pageNo_1", document.html().toString());
                    files = new ConcurrentHashMap<>();
                    files.put(all_fileName + "_pageNo_1", file);
                    item.put("data", data);
                    success = true;
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
                Thread.sleep(1500);
                logger.info(e);
                System.err.println("爬虫过程出现异常, 尝试重新爬取");
                continue;
            }
        }
        if(success == true) {
            return item;
        } else {
            throw new Exception(url+"爬取失败");
        }
    }
}
